﻿using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using ZhongJia.Core;
using ZhongJia.Core.Utility;
using ZhongJia.Core.UI;
using System.Linq;
using ZhongJia.Core.Extensions;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using System.Security.Claims;
using GuanQL.Core.Stores;
using GuanQL.Core;
using GuanQL.Service.Medias;
using GuanQL.Core.Domain.Accounts;
using GuanQL.Service.Accounts.Dto;

namespace ZhongJia.Community.Service.Accounts
{
    public class GQLUserManager<TUser> : UserManager<TUser> where TUser : User
    {
        private readonly GQLDbContext _dbContext;
        private readonly IWebContext _webContext;
        private readonly PictureService _pictureService;
        private readonly AppSettings _appSettings;

        public GQLUserManager(
            IUserStore<TUser> store,
            IOptions<IdentityOptions> optionsAccessor,
            IPasswordHasher<TUser> passwordHasher,
            IEnumerable<IUserValidator<TUser>> userValidators,
            IEnumerable<IPasswordValidator<TUser>> passwordValidators,
            ILookupNormalizer keyNormalizer,
            IdentityErrorDescriber errors,
            IServiceProvider services,
            ILogger<UserManager<TUser>> logger,
            GQLDbContext dbContext,
            IWebContext webContext,
            PictureService pictureService,
            AppSettings appSettings)
                : base(store, optionsAccessor, passwordHasher,
                      userValidators, passwordValidators,
                      keyNormalizer, errors, services, logger)
        {
            _dbContext = dbContext;
            _webContext = webContext;
            _pictureService = pictureService;
            _appSettings = appSettings;
        }

        public async Task<User> Login(string phoneNumber, string verificationCode)
        {
            //if (!_appSettings.IsDevelop && !await _dbContext.Set<SMSRecord>().AnyAsync(u => u.Data == verificationCode && u.Mobile == phoneNumber
            //          && u.Created > SystemClock.Now.AddMinutes(-10) && u.TenantId == _webContext.TenantId
            //          && u.Scene == SMSScene.LoginVerificationCode))
            //    throw new UserFriendlyException("验证码错误");

            var user = await _dbContext.Set<User>().FirstOrDefaultAsync(t => t.PhoneNumber == phoneNumber && t.TenantId == _webContext.TenantId);
            if (user == null)
            {
                return await CreateUserAsync(string.Empty, phoneNumber, phoneNumber, RandomHelper.GetRandomString(6), GlobleConsts.Role.Register);
            }
            return user;
        }

        public async Task<User> AdminLogin(AdminLoginInput request)
        {
            var user = await _dbContext.Set<User>().Include(u => u.Avatar)
                        .Include(u => u.Roles).ThenInclude(r => r.Role)
                        .FirstOrDefaultAsync(u => u.UserName == request.UserName);
            if (user == null || !await CheckPasswordAsync((TUser)user, request.Password))
                throw new UserFriendlyException("用户名或密码错误");

            return user;
        }

        public async Task<Decimal> GetAmount()
        {
            var user = await _dbContext.Users.FirstAsync(u => u.Id == _webContext.CurrentUser.Id);
            return user.Amount;
        }

        public async Task<IPagedList<UserAmountHistory>> GetAmountHistory(PageInput request)
        {
            return await _dbContext.Set<UserAmountHistory>().Where(h => h.UserId == _webContext.CurrentUser.Id).ToPagedList(request);
        }

        public async Task<User> CreateUserAsync(string name, string userName, string phoneNumber, string password, string role
            , bool phoneNumberConfirmed = false, int districtId = 0)
        {
            var avatars = await _pictureService.GetAvatars();
            var avatar = avatars[RandomHelper.GetRandom(avatars.Count)];
            var user = new User
            {
                Name = name,
                AvatarId = RandomHelper.GetRandomOf(avatars.ToArray()).Id,
                UserName = userName,
                TenantId = _webContext.TenantId,
                PhoneNumber = phoneNumber,
                PhoneNumberConfirmed = phoneNumberConfirmed,
            };
            //if (role == GlobleConsts.Role.Agents)
            //{
            //    user.Agent = new Agent
            //    {
            //        DistrictId = districtId
            //    };
            //}
            user.Claims.Add(new IdentityUserClaim<Guid>
            {
                ClaimType = ClaimTypes.UserData,
                ClaimValue = _webContext.TenantId.ToString()
            });
            user.Claims.Add(new IdentityUserClaim<Guid>
            {
                ClaimType = ClaimTypes.Role,
                ClaimValue = role
            });
            user.AvatarId = avatar.Id;
            var result = await CreateAsync((TUser)user, password);
            if (result.Succeeded)
            {
                await AddToRoleAsync((TUser)user, role);
            }
            else
            {
                throw new UserFriendlyException("注册失败!");
            }
            return user;
        }

        //public async Task Edit(EditInfoInput request)
        //{
        //    var user = await _dbContext.Set<User>().FirstOrDefaultAsync(u => u.Id == _webContext.CurrentUser.Id
        //                 && u.TenantId == _webContext.TenantId);
        //    if (user == null)
        //        throw new UserFriendlyException("用户不存在!");

        //    user.NickName = request.NickName;
        //    user.AvatarId = request.AvatarId;
        //  //  user.Gender = request.Gender;

        //    await base.UpdateAsync((TUser)user);
        //}
    }
}
